#!/bin/bash
# 达梦8备份
# 30 5 * * * source /etc/profile && sh /sumz/script/dm_bak.sh > /dev/null 2>&1
# 定义备份目录
bakurl="/sumz-bak/data_bak/dm_bak_file"

username="VOC_DATA"
password='XXXxxx'
connurl='192.168.1.1:54321'

# 定义需要备份的项目名
schemaslist=("VOC_DATA")

# 计算项目数量
num_projects=${#schemaslist[@]}

# 获取当前星期几
ntime=$(date -d "$(date +%Y-%m-%d)" +%w)

mkdir -p $bakurl

# 检查磁盘空间
check_disk_space() {
    local avail_space=$(df -h "$bakurl" | awk 'NR==2 {print $4}')
    if [[ $avail_space < "10G" ]]; then
        echo "磁盘空间不足: $avail_space" | tee -a "$LOG_FILE"
        exit 1
    fi
}

# 备份函数
backup_project() {
    project_name=$1
    mkdir -p "$bakurl/$project_name"
    rm -f $bakurl/$project_name/voc_data_backup.log
    /sumz/dm8/bin/dexp USERID="$username/$password@$connurl" SCHEMAS=$project_name FILE=$bakurl/$project_name/${project_name}_$(date +%Y-%m-%d_%H_%M).dump.compresse LOG=voc_data_backup.log COMPRESS=Y
}

# 删除一个月以前的文件（除星期五以外）
delete_old_files() {
    project_name=$1
    # 计算一个月前的时间戳
    rtime=$(date -d "$(date +%Y-%m-%d -d '-7 day')" +%s)
    cd "$bakurl/$project_name"
    for filename in $(ls "$bakurl/$project_name")
    do
        fntime=$(date -d $(ls --full-time $filename | awk {'print $6'}) +%w)
        baktime=$(date -d $(ls --full-time $filename | awk {'print $6'}) +%s)
        if [ $rtime -gt $baktime ] && [ $fntime -ne 5 ]
        then
            rm -f "$bakurl/$project_name/$filename"
        fi
    done
}

check_disk_space
# 备份和删除文件
for ((i=num_projects-1; i>=0; i--))
do
    backup_project "${schemaslist[$i]}"
    delete_old_files "${schemaslist[$i]}"
done
